package com.itheima.reggie.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    //根据分类id查询菜品列表
    @GetMapping("/dish/list")
    public ResultInfo findByCategoryId(Long categoryId) {
        //0. 约定好缓存之后在Redis中的键
        String key = "dish_" + categoryId;

        //1. 先从Redis中进行查询
        List dishList = (List) redisTemplate.opsForValue().get(key);
        if (CollectionUtil.isNotEmpty(dishList)) {
            log.info("从Redis中获取到了菜品数据");

            //2. 如果查询到了,直接返回
            return ResultInfo.success(dishList);
        } else {
            log.info("从Mysql中获取到了菜品数据");

            //3. 如果查询不到,再去数据库查询,并将查询结果缓存到Redis中,再返回
            //3-1 从数据库查询
            dishList = dishService.findByCategoryId(categoryId);

            //3-2 换存到Redis中
            redisTemplate.opsForValue().set(key, dishList);

            //3-3返回
            return ResultInfo.success(dishList);
        }
    }
}
